package com.wang.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.project.model.entity.User;
import com.wang.project.model.entity.UserKey;
import com.wang.project.constant.UserConstant;
import com.wang.project.model.vo.pay.RefreshKeyVo;
import com.wang.project.service.UserKeyService;
import com.wang.project.mapper.UserKeyMapper;
import com.wang.project.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 胡歌的腿毛
 * @description 针对表【user_key】的数据库操作Service实现
 * @createDate 2023-09-13 16:46:08
 */
@Service
public class UserKeyServiceImpl extends ServiceImpl<UserKeyMapper, UserKey>
        implements UserKeyService {

    @Resource
    private UserService userService;

    /**
     * 刷新用户的ak和sk
     * 当一个月到期后，之前的ak sk过期，提醒用户需要手动刷新ak sk
     *
     * @param httpServletRequest
     * @return
     */
    @Override
    public RefreshKeyVo refreshKey(HttpServletRequest httpServletRequest) {
        RefreshKeyVo refreshKeyVo = new RefreshKeyVo();
        User loginUser = userService.getLoginUser(httpServletRequest);
        QueryWrapper<UserKey> userKeyQueryWrapper = new QueryWrapper<>();
        userKeyQueryWrapper.eq("user_id", loginUser.getId());
        UserKey userKey = this.getOne(userKeyQueryWrapper);
        loginUser.setAccessKey(userKey.getAccessKey());
        loginUser.setSecretKey(userKey.getSecretKey());

        loginUser.setLeftRefreshKeyTime(UserConstant.REFRESHKEYTIME);

        //刷新ak sk
        userService.updateById(loginUser);
        refreshKeyVo.setAccessKey(userKey.getAccessKey());
        refreshKeyVo.setSecretKey(userKey.getSecretKey());
        return refreshKeyVo;
    }
}




